package com.dayuanit.dy14.atm.demo2.dy14atmservice.service.impl;

import com.dayuanit.dy14.atm.demo2.dy14atmcommon.exception.BizException;
import com.dayuanit.dy14.atm.demo2.dy14atmcommon.vo.LoginVO;
import com.dayuanit.dy14.atm.demo2.dy14atmcommon.vo.RegistVO;
import com.dayuanit.dy14.atm.demo2.dy14atmdao.entity.User;
import com.dayuanit.dy14.atm.demo2.dy14atmdao.mapper.UserMapper;
import com.dayuanit.dy14.atm.demo2.dy14atmservice.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Value("${md5.salt}")
    private String md5Salt;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User loadUser(String username) {
        User user = userMapper.getUserByUserName(username);
//        System.out.println(">>>>>" + user.getUsername());
        return user;
    }

    @Override
    public User login(LoginVO loginVO) {
        User user = userMapper.getUserByUserName(loginVO.getUsername());
        if (null == user) {
            throw new BizException("用户不存在或者密码错误");
        }

        String pwdMingwen = loginVO.getPassword() + loginVO.getUsername() + md5Salt;
        String pwdSign = DigestUtils.md5Hex(pwdMingwen);
        if (!user.getPassword().equals(pwdSign)) {
            throw new BizException("用户不存在或者密码错误");
        }

        return user;
    }

    @Override
    public void regist(RegistVO registVO) {
        if (!registVO.getConfirmPwd().equals(registVO.getPassword())) {
            throw new BizException("两次输入的密码不相等");
        }

        User user = userMapper.getUserByUserName(registVO.getUsername());
        if (null != user) {
            throw new BizException("用户名已存在");
        }

        String pwdMingw = registVO.getPassword() + registVO.getUsername() + md5Salt;
        String pwdSign = DigestUtils.md5Hex(pwdMingw);
        user = new User();
        user.setCreateTime(new Date());
        user.setPassword(pwdSign);
        user.setUsername(registVO.getUsername());
        int rows = userMapper.insert(user);
        if (1 != rows) {
            throw new BizException("注册失败");
        }
    }
}
